package com.leyou.sms.mq;

import com.leyou.common.constants.MQConstants;
import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.SmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;


/**
 * @author BaiZY on 2020/9/2.
 * @version 1.0
 */
@Component
@Slf4j
public class MessageListener {


    private final SmsUtils smsUtils;

    public MessageListener(SmsUtils smsUtils) {
        this.smsUtils = smsUtils;
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.QueueConstants.SMS_VERIFY_CODE_QUEUE, durable = "true"),
            exchange = @Exchange(name = MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY
    ))
    public void listenVerifyCodeMessage(Map<String, String> msg) {
        if (CollectionUtils.isEmpty(msg)){
            //消息为空,不处理
            return;
        }
        String phone = msg.get("phone");

        if (!RegexUtils.isPhone(phone)){
            //手机号有误,不处理
            return;
        }

        String code = msg.get("code");
        if (!RegexUtils.isCodeValid(code)){
            //验证码有误,不处理
            return;
        }

        //System.out.println("【SMS服务】");
        //发送短信
        try {
            smsUtils.sendVerifyCode(phone,code);
            log.info("【SMS服务】,{}:短信验证码发送成功",phone);
        } catch (Exception e) {
            log.info("【SMS服务】短信验证码发送失败",e);
        }
    }
}
